package utils

import (
	"strconv"
	"time"
)

// GetAge 根据身份证号码获取用户年龄
func GetAge(idCardNo string) int {
	// {
	// 	tmpIDCard := idCard
	// 	tmp := []byte(tmpIDCard)
	// 	if IsValidCitizenNo(&tmp) == false {
	// 		return -1
	// 	}
	// }
	var mapmou = map[string]int{"January": 1, "february": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
	now := time.Now()
	nowYear := now.Year()                 // 年
	nowMo := mapmou[now.Month().String()] // 月
	nowDay := now.Day()                   // 日
	//fmt.Println(nowYear, nowMo, nowDay)
	idcardYear, _ := strconv.Atoi(_substr(idCardNo, 6, 4)) // 年
	idcardMo, _ := strconv.Atoi(_substr(idCardNo, 10, 2))  // 月
	idcardDay, _ := strconv.Atoi(_substr(idCardNo, 12, 2)) // 日
	//fmt.Println(idcardYear, idcardMo, idcardDay)
	//fmt.Println("idCard:" + idCard)
	age := nowYear - idcardYear // 如果计算虚岁需这样：age := now_year - idcard_year+1
	if nowYear < idcardYear {
		age = 0
	} else {
		if nowMo < idcardMo {
			age = age - 1
		} else {
			if nowDay < idcardDay {
				age = age - 1
			}
		}
	}
	return age
}

func _substr(str string, start, length int) string {

	rs := []rune(str)
	rl := len(rs)
	end := 0
	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length
	if start > end {
		start, end = end, start
	}
	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}
	return string(rs[start:end])
}
